import time
from DrissionPage import ChromiumPage as Chromium
def monitor_game_status():
    
    """监控游戏状态并执行自动投注"""
     # 初始化投注参数
    base_bet_amounts = [1,2,4]  # 基础倍投金额序列
    max_attempts_per_round = len(base_bet_amounts)  # 每轮尝试次数由数组长度决定
    current_amount_index = 0  # 当前投注金额索引
    waiting_for_next_sequence = False  # 是否等待下一个9局序列
    last_bet_type = None  # 上次投注类型
    consecutive_losses = 0  # 连续未中次数
    round_count = 0  # 当前轮数
    max_rounds = 3  # 最大轮数限制
    last_history_result = None
    has_pending_bet = False  #是否有待确认的投注
    # 初始化浏览器
    tab = Chromium().latest_tab
    bool = tab.get('https://star.scngsp.com/games/pc28/3?oddsMapId=4&mode=chat')
    if not bool:
        print("页面加载失败")
        return

    # 初始化期号
    if not hasattr(monitor_game_status, 'last_period'):
        current_period = get_current_period(tab)
        if current_period:
            monitor_game_status.last_period = current_period
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 初始化期号：{current_period}")
    
    try:
        print("开始自动投注监控")
        while True:  # 主循环
            try:
                current_period = get_current_period(tab)
                if not current_period:
                    print("无法获取期号，等待30秒后重试")
                    time.sleep(5)
                    continue
                
                # 期号没变化，继续等待
                if current_period == monitor_game_status.last_period:
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 等待开奖，当前期号：{current_period}")
                    time.sleep(5)
                    continue
                
                # 期号发生变化
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 新一期开始，期号从 {monitor_game_status.last_period} 变更为 {current_period}")
                monitor_game_status.last_period = current_period
                
                # 等待55秒后开始查询结果
                print("等待55秒后开始查询开奖结果...")
                time.sleep(55)
                
                # 开始查询结果，每5秒一次，最多查询25次
                for check_count in range(25):
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 第 {check_count + 1} 次查询结果")
                    current_history = get_history_result(tab)
                    
                    if not current_history:
                        print("获取历史结果失败，5秒后重试")
                        time.sleep(5)
                        continue
                    
                    # 检查结果是否更新
                    if last_history_result is None or (
                        current_history['last_number'] != last_history_result['last_number'] or
                        current_history['last_result'] != last_history_result['last_result']
                    ):
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 检测到新结果: {current_history['last_number']} - {current_history['last_result']}")
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 历史数字: {current_history['numbers']}")
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 历史龙虎: {current_history['dragon_tiger']}")
                        
                        last_history_result = current_history  # 先更新历史结果
                        
                        # 如果有待确认的投注，检查结果并更新状态
                        if has_pending_bet and last_bet_type:
                            if last_bet_type in current_history['last_result']:
                                print("上期投注中奖，重置所有参数")
                                current_amount_index = 0
                                waiting_for_next_sequence = False
                                consecutive_losses = 0
                                round_count = 0
                                base_bet_amounts = [10,20,40]
                                has_pending_bet = False
                                last_bet_type = None
                            else:
                                print("上期投注未中奖")
                                consecutive_losses += 1
                                has_pending_bet = False
                                if consecutive_losses >= max_attempts_per_round:
                                    # waiting_for_next_sequence = True  # 删除这行
                                    current_amount_index = 0
                                    consecutive_losses = 0  # 重置连续未中次数
                                    round_count += 1
                                    if round_count ==1:
                                        base_bet_amounts = [8,16,32]
                                    if round_count ==2:
                                        base_bet_amounts = [64,128,256]
                                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 本轮结束，进入第{round_count + 1}轮 , 下注金额变成 {base_bet_amounts}")
                                else:
                                    current_amount_index = min(current_amount_index + 1, len(base_bet_amounts) - 1)
                            
                            # 处理完投注结果后直接跳出查询循环
                            break

                        # 如果没有待确认的投注，检查是否需要新投注
                        if not waiting_for_next_sequence and round_count < max_rounds:
                            missing_dragon = check_consecutive_missing(current_history['dragon_tiger'], '龙')
                            missing_tiger = check_consecutive_missing(current_history['dragon_tiger'], '虎')
                            
                            if (missing_dragon or missing_tiger) and not has_pending_bet:
                                bet_type = '龙' if missing_dragon else '虎'
                                current_amount = base_bet_amounts[current_amount_index] * 100
                                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 第{round_count + 1}轮 开始投注 {bet_type}, 金额: {current_amount}")
                                
                                if place_bet(tab, current_amount, bet_type):
                                    last_bet_type = bet_type
                                    has_pending_bet = True
                                    print("投注成功，等待开奖结果")
                        
                        break  # 无论是否进行新投注，都跳出查询循环
                    else:
                        print("结果未更新，5秒后重试")
                        time.sleep(5)
                
                # 本轮结束，等待30秒后继续主循环
                time.sleep(30)
                
            except Exception as e:
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 监控过程发生错误: {e}")
                time.sleep(30)
                
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 程序发生错误: {e}")
    finally:
        tab.quit()

def get_current_period(tab):
    """获取当前期号"""
    try:
        # 先找到包含"期 开奖号码"的span元素，然后获取其前一个兄弟元素
        period_element = tab.ele('xpath=//span[text()="期 开奖号码"]/preceding-sibling::span[1]')
        if period_element:
            current_period = period_element.text.strip()
            return current_period
        
        print("未找到期号元素")
        return None
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 获取期号失败: {e}")
        return None

def get_history_result(tab):
    """获取历史结果"""
    try:
        amount_input = tab.ele('.fakeInput')
        amount_input.input('历史')
        bet_button = tab.ele('text=发送')   
        bet_button.click()   
        time.sleep(5)
        
        history_text = tab.ele('xpath=(//div[contains(text(), "历史答案")])[last()]').text
        lines = history_text.split('\n')
        numbers = [int(num) for num in lines[0].replace('历史答案：', '').strip().split()]
        dragon_tiger = lines[1].replace('历史答案：', '').strip().split()
        
        return {
            'numbers': numbers,
            'dragon_tiger': dragon_tiger,
            'last_number': numbers[-1],
            'last_result': dragon_tiger[-1]
        }
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 获取历史结果失败: {e}")
        return None

def check_consecutive_missing(dragon_tiger_list, target_type, count=9):
    """
    检查最近count局是否缺失某个类型
    :param dragon_tiger_list: 龙虎历史列表
    :param target_type: 目标类型 ('龙' 或 '虎')
    :param count: 检查的局数，默认9局
    :return: 是否连续缺失
    """
    # 获取最后count局的记录
    recent_results = dragon_tiger_list[-count:]
    print(recent_results)
    # 计算目标类型出现的次数
    target_count = recent_results.count(target_type)
    # 如果一次都没出现，返回True
    return target_count == 0

def place_bet(tab, amount, bet_type):
    """
    执行下注操作
    :param tab: 浏览器标签页
    :param amount: 下注金额
    :param bet_type: 下注类型（龙或虎）
    :return: 下注是否成功
    """
    try:
        # 输入金额
        amount_input = tab.ele('.fakeInput')
        amount_input.input(bet_type+str(amount))
        time.sleep(3)
        # 点击确认下注
        confirm_button = tab.ele('text=发送')
        confirm_button.click()

        return True
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 下注失败: {str(e)}")
        return False


# def login(tab):
#     """
#     执行登录操作
#     :param tab: 浏览器标签页
#     :return: 登录是否成功
#     """
#     try:
#         # 输入用户名
#         username_input = tab.ele('#username')
#         username_input.input('your_username')
        
#         # 输入密码
#         password_input = tab.ele('#password')
#         password_input.input('your_password')
        
#         # 点击登录按钮
#         login_button = tab.ele('text=登录')
#         login_button.click()
        
#         time.sleep(2)  # 等待登录完成
#         return True
#     except Exception as e:
#         print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 登录失败: {str(e)}")
#         return False

if __name__ == '__main__':
    monitor_game_status()